package com.cskaoyan.util;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * @author 楚夏三分
 * @datetime 2022/12/31 10:45
 * @description: TODO: 反射工具类
 */
public class ReflectUtil {

    /**
     * TODO: 获取类的所有成员变量名的List列表
     * @param clazz 传入获取类的Class对象
     * @return 返回List
     */
    public static ArrayList<String> getConfigNamesByClazz(Class clazz){
        Field[] declaredFields = clazz.getDeclaredFields();
        ArrayList<String> arrayList = new ArrayList<>();
        for (Field field : declaredFields) {
            String name = field.getName();
            arrayList.add(name);
        }
        return arrayList;
    }

    /**
     * TODO: 获取对象的所有成员变量名及其对应Value值的toString字符串Map
     * @param t 传入需要获取数据的对象
     * @param <T> 类型同传入的对象
     * @return Map
     */
    public static <T> HashMap<String,String> getConfigUpdateMsgMapByClazz(T t){
        HashMap<String,String> map = new HashMap<>();
        Field[] declaredFields = t.getClass().getDeclaredFields();
        for (Field field : declaredFields) {
            field.setAccessible(true);
            Class<?> type = field.getType();
            String fieldValue;
            Class<? extends String> aClass = "a".getClass();
            try {
                if (type == aClass){
                    fieldValue = (String)field.get(t);
                }else {
                    fieldValue = field.get(t).toString();
                }
            }catch (IllegalAccessException e){
                e.printStackTrace();
                throw new IllegalArgumentException("IllegalArgumentException");
            }
            String fieldName = field.getName();
            map.put(fieldName,fieldValue);
        }
        return map;
    }
}
